<template>
  <div ref="container"></div>
</template>

<script setup lang="ts">
import type { ServerScore } from '~/types';
import * as echarts from 'echarts';
const props = defineProps({
  data: {
    type: Array as PropType<ServerScore[]>,
    required: true
  },
  pageNum: {
    type: Number,
    default: 1
  }
});
const container = ref(null);
let myChart: any;

function initChart(data: ServerScore[]) {
  if (!myChart) {
    myChart = echarts.init(container.value);
  }
  const series: any = [];
  const colors = ['#008CFF', '#14CC8F', '#E76D36', '#FF930F', '#17B4BF', '#6C7EE4'];
  data.forEach((d, i) => {
    series.push({
      name: d.county,
      type: 'boxplot',
      data: [
        {
          value: d.scores,
          itemStyle: {
            color: colors[i] + '98',
            borderColor: colors[i]
          }
        }
      ]
    });
  });

  const option = {
    color: colors,
    legend: {
      itemWidth: 8,
      itemHeight: 8,
      // type: 'scroll',
      orient: 'horizontal',
      top: 20,
      left: 16,
      itemStyle: {
        borderRadius: 0,
        borderWidth: 0
      },
      textStyle: {
        color: 'rgba(255,255,255,0.7)',
        fontWeight: 400,
        fontSize: 12
      }
    },
    xAxis: {
      type: 'category',
      data: [],
      boundaryGap: true,
      nameGap: 30,
      splitArea: {
        show: false
      },
      splitLine: {
        show: false
      },
      axisTick: {
        show: false
      }
    },
    grid: {
      top: 65,
      right: 20,
      bottom: 20,
      left: 50
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true,
        lineStyle: {
          color: '#19ECFF44',
          type: 'dashed'
        }
      }
    },
    series: series
  };
  myChart.clear();
  myChart.setOption(option);
}

watch(
  () => props.data,
  (val) => {
    if (val) {
      initChart(val);
    }
  }
);

watch(
  () => props.pageNum,
  () => {
    initChart(scores.value);
  }
);
const scores = computed(() => {
  return props.data.slice((props.pageNum - 1) * 6, props.pageNum * 6);
});
onMounted(() => {
  if (scores.value) {
    initChart(scores.value);
  }
});
</script>
